// @flow
import React from 'react'
import { DatePicker, Form, Input, Select, Button, message, Upload, Icon } from 'antd'
import { getSpecs } from 'utils/GeneralOptions'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import styles from './Home.css'
import moment from 'moment'
// import Tags from 'components/Tags'
import DeviceContactList from 'components/DeviceContactList'
const Dragger = Upload.Dragger
import { connect } from 'react-redux'

type Props = {
  userId: string,
  form: Object,
  history: Object,
}

const FormItem = Form.Item
const Option = Select.Option

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 14 }
  }
}

const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0
    },
    sm: {
      span: 14,
      offset: 6
    }
  }
}

type States = {
  deviceData: Object,
  pagination: Object,
  loading: boolean,
  specs: Array<any>,
  customers: Array<Object>,
  deviceTypes: Array<Object>,
  deviceStatus: Array<Object>,
  dataSource: Array<Object>,
  owner: Array<Object>,
  tagData: Array<string>,
  imageUrl: string,
  remoteImageUrl: string,
  contactData: Array<Object>,
  fileList: Array<Object>,
  customerId: string
}
class DeviceEdit extends React.Component {
  props: Props
  state: States
  goBack: Function
  checkNum: Function
  changeTags: Function
  changeFile: Function
  beforeUpload: Function
  getDeviceData: Function
  getContact: Function
  changeFile1: Function
  getFiles: Function
  changeCustomer: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      deviceData: {},
      pagination: {},
      loading: false,
      specs: [],
      customers: [],
      deviceTypes: [],
      deviceStatus: [],
      dataSource: [],
      owner: [],
      imageUrl: '',
      remoteImageUrl: '',
      tagData: [],
      contactData: [],
      fileList: [],
      customerId: ''
    }

    this.goBack = this.goBack.bind(this)
    this.changeTags = this.changeTags.bind(this)
    this.checkNum = this.checkNum.bind(this)
    this.changeFile = this.changeFile.bind(this)
    this.beforeUpload = this.beforeUpload.bind(this)
    this.getDeviceData = this.getDeviceData.bind(this)
    this.getContact = this.getContact.bind(this)
    this.changeFile1 = this.changeFile1.bind(this)
    this.getFiles = this.getFiles.bind(this)
    this.changeCustomer = this.changeCustomer.bind(this)
  }

  componentWillMount () {
    this.getDeviceData()
    const { location } = this.props.history
    const { data } = location.state
    let imageUrl = data.imageUrl
    const index = imageUrl.lastIndexOf('/')
    imageUrl = imageUrl.substring(index + 1, imageUrl.length)
    this.setState({
      imageUrl: imageUrl,
      remoteImageUrl: data.imageUrl,
      tagData: data.keyName.split(',')
    })
    this.getFiles(data)
  }

  componentDidMount () {
    this.getCustomers()
    this.getSpecDatas()
    this.getStatus()
    this.getUsers()
  }

  changeCustomer (value) {
    this.setState({
      customerId: value
    })
  }

  getFiles (data) {
    universalFetch(`${__SERVICE_API__}device/devices/${data.id}/files`)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({
            code: json.code,
            message: json.message
          }))
        }
        this.setState({
          fileList: json.result.map((d, i) => {
            let ob = {}
            ob['uid'] = d.id
            ob['name'] = d.fileName
            ob['size'] = d.size
            ob['url'] = d.fileUrl
            ob['status'] = 'done'
            return ob
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  getDeviceData () {
    const { location } = this.props.history
    const { data } = location.state
    universalFetch(`${__SERVICE_API__}device/devices/${data.id}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          deviceData: json.result,
          contactData: json.result.contacts || [],
          customerId : json.result.customer ? json.result.customer.id : ''
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  checkNum (rule, value, callback) {
    const checkReg = /^[0-9][Z0-9_]*$/
    if (value && !checkReg.test(value)) {
      callback('只能以数字开头, 且只能包含数字和下划线')
    } else {
      callback()
    }
  }

  getSpecDatas = () => {
    const { location } = this.props.history
    const { data } = location.state
    getSpecs(data.type, (json) => {
      this.setState({
        specs: json.result.map((d, i) => {
          return <Option key={d.id} value={d.value}>{d.label}</Option>
        })
      })
    })
  }

  handleSpecChange () {

  }

  goBack () {
    const { history } = this.props
    history.push('/business/device-info')
  }

  changeTags (tagData) {
    this.setState({
      tagData
    })
  }

  changeFile (info) {
    const response = info.file.response
    if (response && response.code === 200000) {
      this.setState({
        imageUrl: response.result.name,
        remoteImageUrl: response.result.url
      })
    }
  }
  changeFile1 (info) {
    let fileList = info.fileList
    // 1. Limit the number of uploaded files
    //    Only to show two recent uploaded files, and old ones will be replaced by the new
    fileList = fileList.slice(-10)
    // 2. read from response and show file link
    fileList = fileList.map((file) => {
      if (file.response) {
        // Component will show file.url as link
        file.url = file.response.result.url
        file.name = file.name
      }
      return file
    })
    // 3. filter successfully uploaded files according to response from server
    fileList = fileList.filter((file) => {
      const status = info.file.status
      if (status === 'done') {
        if (file.response) {
          return file.response.code === 200000
        }
      }
      return true
    })
    this.setState({ fileList: fileList })
  }
  beforeUpload (file) {
    const type = file.type.toLocaleLowerCase()
    if (type.indexOf('image/') === -1) {
      message.error('只能上传图片', 3)
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('图片必须小于2MB!')
    }
    return type.indexOf('image/') > -1
  }
  getContact (data: Array<Object>) {
    this.setState({
      contactData: data
    })
  }
  /**
   * 提交表单
   * @param  {[type]} e [description]
   * @return {[type]}   [description]
   */
  handleSubmit = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) {
        return false
      }
      this.setState({
        loading: true
      })
      const { imageUrl, contactData, fileList } = this.state
      const values1 = {
        ...Object.assign({}, fieldsValue, { imageUrl }),
        'contacts': contactData,
        'keyName': this.state.tagData.join(','),
        'produceDate': fieldsValue.produceDate
          ? fieldsValue['produceDate'].hour(0).minute(0).second(0).format('YYYY-MM-DDTHH:mm:ss.SSSZ') : '',
        'operationDate': fieldsValue.operationDate
          ? fieldsValue['operationDate'].hour(0).minute(0).second(0).format('YYYY-MM-DDTHH:mm:ss.SSSZ') : ''
      }
      const values = {
        ...Object.assign({}, values1, { fileList })
      }
      const { location } = this.props.history
      const { data } = location.state
      // console.log('values----------------------')
      // console.log(`${__SERVICE_API__}device/devices/${data.id}`)
      // console.log(values)
      universalFetch(`${__SERVICE_API__}device/devices/${data.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(values)
      })
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          loading: false
        })
        message.success('设备修改成功')
        this.props.history.push('/business/device-info')
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
        this.setState({
          loading: false
        })
        message.error('设备修改失败： ' + err.message)
      })
    })
  }

  getCustomers () {
    universalFetch(`${__SERVICE_API__}device/customers?userId=${this.props.userId}&pageSize=20000`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          customers: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getUsers () {
    universalFetch(`${__SERVICE_API__}sys/users?pageSize=20000`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          owner: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }
  getStatus () {
    const types = ['deviceStatus', 'dataSource']
    // $FlowFixMe
    universalFetch(`${__SERVICE_API__}device/conditions?types=${types}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          deviceStatus: json.result.deviceStatus,
          dataSource: json.result.dataSource
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  render () {
    const { getFieldDecorator } = this.props.form
    const { customers, loading, deviceStatus, dataSource, owner, remoteImageUrl, deviceData } = this.state
    // const { location } = this.props.history
    // const { data } = location.state
    const token = localStorage.getItem('asset_token')
    const specFieldDecorator = deviceData.spec
      ? getFieldDecorator('spec', {
        initialValue: deviceData.spec
      })
      : getFieldDecorator('spec', {
      })
    let props1 = {
      name: 'file',
      multiple: true,
      showUploadList: true,
      headers:{ 'X-Auth':token },
      action: `${__SERVICE_API__}static/statics`,
      fileList: this.state.fileList,
      onChange: this.changeFile1
    }
    return (
      <div className={styles['main']}>
        <Form onSubmit={this.handleSubmit}>
          <FormItem {...formItemLayout} label='设备编号' hasFeedback>
            {getFieldDecorator('deviceNo', {
              rules: [
                { required: true, message: '请填写设备编号', whitespace: true },
                { validator: this.checkNum }
              ],
              initialValue: deviceData.deviceNo
            })(
              <Input placeholder='请填写设备编号' ref={(e) => {
                document.querySelector('#deviceNo').focus()
              }} />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='设备模板'>
            {getFieldDecorator('tdeviceId', {
              initialValue: deviceData.tdeviceId
            })(
              <span>{deviceData.tdevice ? deviceData.tdevice.name : '无'}</span>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='型号'>
            {specFieldDecorator(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} style={{ width: 280 }}
                placeholder='请选择型号'
                onChange={this.handleSpecChange}>
                {this.state.specs}
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='名字' hasFeedback>
            {getFieldDecorator('name', {
              rules: [
                { required: true, message: '请填写名字', whitespace: true }
              ],
              initialValue: deviceData.name
            })(
              <Input placeholder='请填写名字' />
            )}
          </FormItem>
          {/* <FormItem {...formItemLayout} label='全称' hasFeedback>
            {getFieldDecorator('fullName', {
              initialValue: deviceData.fullName
            })(
              <Input placeholder='请填写全称' />
            )}
          </FormItem> */}
          <FormItem {...formItemLayout} label='产品编号' hasFeedback>
            {getFieldDecorator('pinCode', {
              initialValue: deviceData.pinCode
            })(
              <Input placeholder='请填写pinCode' />
            )}
          </FormItem>

          <FormItem {...formItemLayout} label='制造商' hasFeedback>
            {getFieldDecorator('certificateNo', {
              initialValue: deviceData.certificateNo
            })(
              <Input placeholder='请填写制造商名称' />
            )}
          </FormItem>
          {/* <FormItem {...formItemLayout} label='键相' hasFeedback>
            {getFieldDecorator('keyName', {
              initialValue: deviceData.keyName ? deviceData.keyName.split(',') : []
            })(
              <div>
                <Input style={{ display:'none' }} placeholder='请填写键相(1,2,3)' />
                <Tags deValue={deviceData.keyName ? deviceData.keyName.split(',') : []} onChange={this.changeTags} />
              </div>
            )}
          </FormItem> */}
          <FormItem {...formItemLayout} label='生产日期'>
            {getFieldDecorator('produceDate', {
              initialValue: deviceData.produceDate ? moment(deviceData.produceDate) : ''
            })(
              <DatePicker placeholder='请选择生产日期' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='投用日期'>
            {getFieldDecorator('operationDate', {
              initialValue: deviceData.operationDate ? moment(deviceData.operationDate) : ''
            })(
              <DatePicker placeholder='请选择投用日期' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='设备状态'>
            {
              getFieldDecorator('status', {
                initialValue: deviceData.status
              })(
                <Select disabled showSearch
                  filterOption={(input, option) => {
                    return option.props.children.indexOf(input) >= 0
                  }} style={{ width:280 }} placeholder='请选择设备状态'>
                  {
                    deviceStatus.map((item, i) => {
                      return <Option key={i} value={item.value}>
                        {item.label}
                      </Option>
                    })
                  }
                </Select>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='设备负责人'>
            {getFieldDecorator('owner', { initialValue: deviceData.owner })(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} style={{ width: 280 }}>
                {
                  owner.map((item, i) => {
                    return <Option key={i} value={item.loginName}>
                      {item.loginName}
                    </Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='数据源'>
            {getFieldDecorator('dataSource', { initialValue: deviceData.dataSource })(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} style={{ width: 280 }}>
                {
                  dataSource.map((item, i) => {
                    return <Option key={i} value={item.value}>
                      {item.label}
                    </Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='所属客户'>
            {getFieldDecorator('customerId', {
              rules: [
                { required: true, message: '请选择所属客户' }
              ],
              initialValue: deviceData.customer ? `${deviceData.customer.id}` : ''
            })(
              <Select showSearch
                filterOption={(input, option) => {
                  return option.props.children.indexOf(input) >= 0
                }} placeholder='请选择客户'
                onChange={this.changeCustomer}
                >
                {
                  customers.map((customer, i) => {
                    return <Option key={i} value={`${customer.id}`}>
                      {customer.name}
                    </Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='联系人'>
            {getFieldDecorator('contacts')(
              <DeviceContactList
                customerId={this.state.customerId}
                contactData={deviceData.contacts}
                getContact={this.getContact}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='设备图片'>
            {
              getFieldDecorator('imageUrl', { initialValue: deviceData.imageUrl })(
                <Upload
                  {...{
                    name: 'file',
                    className: styles['avatar-uploader'],
                    action: `${__SERVICE_API__}static/statics`,
                    headers:{ 'X-Auth':token },
                    onChange: this.changeFile,
                    beforeUpload: this.beforeUpload,
                    showUploadList: false
                  }}
                  >
                  {
                    remoteImageUrl
                    ? <div className={styles['image-preview']}>
                      <img src={remoteImageUrl} style={{ width: '100%' }} />
                      <div className={styles['over-avatar']}>
                        更换图片
                      </div>
                    </div>
                    : <Button style={{ width: '150px' }}>
                      <Icon type='upload' />上传图片
                    </Button>
                  }
                </Upload>
              )
            }
          </FormItem>
          <FormItem {...formItemLayout} label='备注' hasFeedback>
            {getFieldDecorator('remark', {
              initialValue: deviceData.remark
            })(
              <Input placeholder='请填写备注' />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='文件'>
            {
              getFieldDecorator('fileUrl', {})(
                <Dragger {...props1}>
                  <p className='ant-upload-drag-icon'>
                    <Icon type='inbox' />
                  </p>
                  <p className='ant-upload-text'>点击或者拖拽文件到该区域</p>
                  <p className='ant-upload-hint'>支持单个或批量上传</p>
                </Dragger>
              )
            }
          </FormItem>
          <FormItem
            {...tailFormItemLayout}
            // className={styles['goBackBtn']}
            >
            <Button type='primary' htmlType='submit'
              loading={loading}
              >修改</Button>
            <Button style={{ marginLeft: '20px' }}
              onClick={this.goBack}
              >返回</Button>
          </FormItem>
        </Form>
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    userId: state.user.userId
  }
}
export default connect(mapStatesToProps, {})(Form.create()(DeviceEdit))
